package com.anrongtec.zcpt.manager;

import android.content.Context;
import android.content.Intent;

import com.anrongtec.zcpt.JWTApp;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.constant.PreferenceKey;
import com.anrongtec.zcpt.db.LiteOrmDBUtil;
import com.anrongtec.zcpt.model.AppModel;
import com.anrongtec.zcpt.utils.ApkUtils;
import com.anrongtec.zcpt.utils.AppCacheUtils;
import com.anrongtec.zcpt.utils.FileUtils;
import com.anrongtec.zcpt.utils.PreferenceUtils;
import com.anrongtec.zcpt.utils.Util;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.lzy.okhttpserver.download.db.DownloadDBManager;
import com.lzy.okhttpserver.listener.DownloadListener;
import com.lzy.okhttputils.request.GetRequest;

import java.io.File;
import java.util.List;

/**
 * 作者：liuhui on 2017/2/13 14:10
 * 邮箱：liu594545591@126.com
 * 描述：APPDownloadManager
 */

public class APPDownloadManager {

    /**
     * 获取downloadManager对象
     * @return
     */
    public static DownloadManager getManager(){
        return DownloadService.getDownloadManager();
    }


    /**
     * 添加下载任务, 监听是第三方的listener
     * @param context
     * @param app		需要下载的app对象
     * @param listener
     */
    public static void addTask(final Context context, AppModel app, DownloadListener listener){
        if (listener == null) {
            listener = new DownloadListener() {
                @Override
                public void onProgress(DownloadInfo downloadInfo) {
                }
                @Override
                public void onFinish(DownloadInfo downloadInfo) {
                    //下载完成后提示安装
                    if (FileUtils.isExist(downloadInfo.getTargetPath())) {
                        ApkUtils.installSilent(context, new File(downloadInfo.getTargetPath()));
                    }
                    //下载完成, 发送广播更新下载的红色提示点
                    sendShowDownloadBroadcost(context);
                }
                @Override
                public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {
                }
            };
        }
        //***********************
        //该app的第一次下载才上报(不是继续下载)
        if (getManager().getDownloadInfo(app.getUrl()) == null) {
            //TODO 上报app下载行为
            String accountId = PreferenceUtils.getInstance(context).getString(PreferenceKey.ACCOUNT_ID);
//			WLData.getInstance().reportEvent(accountId, Events.APP_DOWNLOAD);

            //如果下载之前就已经安装了, 说明这次下载是更新
            if (ApkUtils.isAvailable(context, app.getAppPackName())) {
                //安装之后再改为false
//				app.setNeedUpgrade(true);
                app.setRemoteSize(app.getSize());
            }
            //TODO 注意区别远程和本地版本号.   第一次下载保存保存包名, 用于区别是否是商店下载的app
            LiteOrmDBUtil.insert(app);

        }
        //************************
        GetRequest request = new GetRequest(Util.getDownloadUrl(app.getUrl()));
        getManager().addTask(app.getAppName(), app.getUrl(), request, listener);
        //缓存app的信息
        AppCacheUtils.getInstance(context).put(app.getUrl(), app);


        sendShowDownloadBroadcost(context);
    }

    /**
     * 发送一个 显示正在下载数量的广播
     * @param context
     */
    public static void sendShowDownloadBroadcost(Context context) {
        Intent intent = new Intent();
        intent.setAction(Constant.action.APP_DOWNLOAD);
//		intent.putExtra(Constant.DATA, getDownloadTaskCount());
        context.sendBroadcast(intent);
    }

    /**
     * 添加下载任务, 监听是管理类自定义的监听(用于统一管理下载, 因为第三方的监听无法直接管理)
     * @param context
     * @param app
     * @param listener
     */
    public static void addTaskNew1(final Context context, AppModel app, final AppDownloadListener listener){
        GetRequest request = new GetRequest(Util.getDownloadUrl(app.getUrl()));
        request.params(JWTApp.getInstance().getBaseInfo());
        getManager().addTask(app.getAppName(), app.getUrl(), request, new DownloadListener() {
            @Override
            public void onProgress(DownloadInfo downloadInfo) {
                listener.progress(downloadInfo);
            }
            @Override
            public void onFinish(DownloadInfo downloadInfo) {
                //下载完成后提示安装
                if (FileUtils.isExist(downloadInfo.getTargetPath())) {
                    ApkUtils.installSilent(context, new File(downloadInfo.getTargetPath()));
                }
                listener.finish(downloadInfo);
            }
            @Override
            public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {
                listener.error(downloadInfo, errorMsg, e);
            }
        });
    }

    public interface AppDownloadListener {
        void progress(DownloadInfo downloadInfo);
        void finish(DownloadInfo downloadInfo);
        void error(DownloadInfo downloadInfo, String errorMsg, Exception e);
    }

    /**
     * 移除任务
     */
    public static void removeTask(String taskKey){
        getManager().removeTask(taskKey);
        sendShowDownloadBroadcost(JWTApp.getInstance().getApplicationContext());
    }


    public static DownloadInfo getDownloadInfo(String taskKey){
        return DownloadDBManager.INSTANCE.get(taskKey);
    }

    /**
     * 获取未下载完成的任务数量(即 状态不是finish)
     */
    public static int getDownloadTaskCount(){
        List<DownloadInfo> allTask = APPDownloadManager.getManager().getAllTask();
        int i = 0;
        for (DownloadInfo downloadInfo : allTask) {
            // && downloadInfo.getState() != DownloadManager.ERROR
            if (downloadInfo.getState() != DownloadManager.FINISH) {
                i++;
            }
        }
        return i;
    }
}

